<template>
    <div class="drugTabItem-view">

      <div class="drug item">

        <el-tooltip v-if="drug.id && !drug.number" effect="dark" content="库存不足" placement="top">
          <i style="color: red" class="el-icon-warning-outline"></i>
        </el-tooltip>

<!--        <el-select-->
<!--          v-model="data.product_name"-->
<!--          filterable-->
<!--          remote-->
<!--          reserve-keyword-->
<!--          placeholder="药品名称"-->
<!--          @change="dataChange" @focus="nameFocus" @keyup.native="inputChange"-->
<!--          :remote-method="remoteMethod"-->
<!--          :loading="loading">-->
<!--          <el-option-->
<!--            v-for="(item,idx) in drugList"-->
<!--            :key="idx.id"-->
<!--            :label="item.product_name"-->
<!--            :value="item.id">-->
<!--          </el-option>-->
<!--        </el-select>-->


        <el-autocomplete
          v-model="data.product_name"
          :fetch-suggestions="querySearch"
          placeholder="药品关键字"
          :trigger-on-focus="false"
          :popper-append-to-body="false"
          @focus="focusInp"
          @change="onChangeInp"
          @clear="clearSl"
          @select="handleSelect">
          <template slot-scope="{ item }">
            <div class="product-item">
              <div class="name">
                <span>{{ item.product_name }}</span>
                <span>({{ item.pack }})</span>
                <span>({{ item.production }})</span>
              </div>
            </div>
          </template>
        </el-autocomplete>


      </div>

      <div class="specifications item">
        <span v-if="!data.product_id" class="gray">包装规格</span>
        <span v-else>{{data.pack}}</span>
      </div>

      <div class="manufacturer item">
        <span v-if="!data.product_id" class="gray">生产厂家</span>
<!--        <span v-else>{{data.production}}</span>-->
        {{data.production}}
      </div>

      <div class="total item">

        <span v-if="data.pri">¥{{data.pri.toFixed(2)}}</span>
        <span v-else>¥0.00</span>
      </div>

      <div class="number item">
        <div class="merge-input" style="align-items: center">
          <el-input v-model.number="data.number" @keyup.native="numberChange"></el-input>
          <div class="line"></div>
<!--          <span style="padding: 0 10px;">{{data.unit}}</span>-->
          <el-select v-model="unit" @change="unitChange">
            <el-option
              v-for="item in units"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </div>
      </div>

      <div class="price item">

        ￥<el-input v-model="data.price" @keyup.native="proving" placeholder="单价(元)"  @input="priceChange" @blur="priceBlur"></el-input>
      </div>

      <div class="total item">

        <span v-if="data.amount">¥{{data.amount.toFixed(2)}}</span>
        <span v-else>¥0.00</span>
      </div>

      <div class="delete item">
        <a @click="deleteClick"><i class="el-icon-delete"></i></a>

      </div>

    </div>
</template>

<script>
    import {getCentralList, getDefault} from '@/api/drugsManagement';

  export default {
        name: "drugTabItem",
        props:{
            data:Object,
            total:Number,
            index:Number,
        },
        data:function () {
            return{
                options:[],
                drugList:[],
                loading:false,
                drug:{},
                units:[],
                unit:'',

                inputList:[],
              // data:{
              //     name:'',
              //     number:0,
              //     unit:'0',
              //     total:0,
              //     price:0,
              // }
            }
        },
        mounted:function(){

        },
        computed:{
            amount:function () {
                let am = 0;
                if (this.data.number && this.data.price){
                    am = Number(this.data.number)*Number(this.data.price)
                }
                this.$set(this.data,"amount",am)
                return am
            }
        },
        methods:{
            unitChange:function(val){
                this.$set(this.data,"unit",val)
                // this.unit = val;
            },
            dataChange:function(val){
                // console.log(val)

                getDefault(val).then((res) => {
                    if (res.code === 200) {
                        if (res.data){
                            this.drug = res.data;
                            this.data.product_id = res.data.id
                            this.data.product_name = res.data.product_name;
                            this.data.pack = res.data.pack;
                            this.data.production = res.data.production;
                            this.data.pri = Number(res.data.price);
                            this.data.price = Number(res.data.price);
                            this.data.number = 0;
                            if (this.drug.number){
                                this.data.number = 1;

                                this.$set(this.data,"amount",Number(this.data.number)*Number(this.data.price))
                                this.$emit('amount-change')
                            }

                            this.units = [res.data.number_unit]
                            if (this.drug.split_piece){
                                this.units.push(res.data.piece_unit)
                            }
                            this.data.unit = res.data.number_unit
                            this.unit = res.data.number_unit
                        }
                    }
                })
            },
            //获取
            remoteMethod(query) {
                // this.product_name = query
                if (query != ""){
                    this.loading = true;
                    this.getDrugsListData({prefix: query,size:10})
                }
            },
            //药品列表
            getDrugsListData(data) {

                getCentralList(data).then((res)=>{
                    this.loading = false;
                    if (res.code == 200){
                        if (res.data.self && res.data.ElasticProduct.length > 0){
                            this.drugList = res.data.ElasticProduct || []
                        }else {
                            this.drugList = []
                        }

                    }else {
                        this.$message.error(res.msg);
                    }
                }).catch((err)=>{
                    this.loading = false;
                })
                // getDrugsList(data).then(res => {
                //     this.loading = false;
                //     if (res.code === 200) {
                //         this.drugList = res.data.data || []
                //     }
                // }).catch((err)=>{
                //     this.loading = false;
                // })
            },
            async querySearch(queryString, cb) {
                let reg = /^[a-zA-Z]+$/.test(queryString)
                if (reg === true) {
                    queryString = queryString.toLowerCase()
                }
                let res = await getCentralList({prefix: queryString.replace(/(^\s*)|(\s*$)/g, ""), size: 10})
                if (res.code === 200 && res.data.self === true) {
                    this.inputList = res.data.ElasticProduct || []
                } else {
                    this.inputList = []
                    this.data.product_name = queryString

                }
                var results = this.inputList;
                cb(results);
            },
            //select获取焦点添加
            focusInp() {
                this.inputList = []
                if (this.index == this.total-1){
                    this.$emit("add-item")
                }
            },
            onChangeInp( val) {
                this.data.product_name = val
                if (val === '') {
                    this.clearSl()
                }else {
                    if (this.drug.id){
                        this.data.product_name = this.drug.product_name;
                    }else {
                        this.data.product_name = "";
                    }
                }
            },
            //select清除
            clearSl(index) {
                this.drug = {};
                this.data.product_id = 0;
                this.data.product_name = ''//名字
                this.data.price = 0
                this.data.amount = 0
                this.data.number = 0
                this.data.pack = "";
                this.data.production = "";
                this.data.pri = 0;
                this.$emit('amount-change')
            },
            handleSelect(val) {
                getDefault(val.id).then(res => {
                    if (res.code === 200 && res.data !== null) {
                        this.drug = res.data;
                        this.data.product_id = res.data.id
                        this.data.product_name = res.data.product_name;
                        this.data.pack = res.data.pack;
                        this.data.production = res.data.production;
                        this.data.pri = Number(res.data.price);
                        this.data.price = Number(res.data.price).toFixed(2);
                        this.data.number = 0;
                        if (this.drug.number){
                            this.data.number = 1;

                            this.$set(this.data,"amount",Number(this.data.number)*Number(this.data.price))
                            this.$emit('amount-change')
                        }

                        this.units = [res.data.number_unit]
                        if (this.drug.split_piece){
                            this.units.push(res.data.piece_unit)
                        }
                        this.data.unit = res.data.number_unit
                        this.unit = res.data.number_unit
                    }
                })
            },
            deleteClick:function () {
                this.$emit("delete-item",this.index)
            },
            nameFocus:function () {
                if (this.index == this.total-1){
                    this.$emit("add-item")
                }
            },
            inputChange:function(){

            },
            priceChange:function () {

            },
            priceBlur:function(){
                this.data.price = Number(this.data.price).toFixed(2);
            },
            numberChange:function(){
                let str = this.data.number+'';
                str=str.replace(/[^\d]/g,0)
                str = Number(str);

                if (this.drug.number && str > this.drug.number){
                    str = this.drug.number
                }else if (!this.drug.number){
                    str = 0
                }
                this.data.number=Number(str)
                if (this.data.price && this.data.price > 0){
                    this.$set(this.data,"amount",Number(this.data.number)*Number(this.data.price))
                    this.$emit('amount-change')
                }
            },
            proving:function() {
                let str = this.data.price + ""
                // this.form.skus[e].Price 是input的值　　
                // 先把非数字的都替换掉，除了数字和.
                str = str.replace(/[^\d.]/g, '');
                // 必须保证第一个为数字而不是.
                str = str.replace(/^\./g, '');
                // 保证只有出现一个.而没有多个.
                str = str.replace(/\.{2,}/g, '');
                // 保证.只出现一次，而不能出现两次以上
                str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
                let index = -1
                for (let i in str) {
                    if (str[i] === '.') {
                        index = i
                    }
                    if (index !== -1) {
                        if (i - index > 2) {
                            str = str.substring(0, str.length - 1)
                        }
                    }
                }
                this.data.price = str;
                if (this.data.number && this.data.number > 0){
                    this.$set(this.data,"amount",Number(this.data.number)*Number(this.data.price))
                    this.$emit('amount-change')
                }
            },
        }
    }
</script>

<style lang="scss">
  @import "@/assets/scss/payOrDrug/drugTabItem.scss";
</style>
